package models

import (
	"comment/util"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type Role struct {
	Id          int    `orm:"pk;auto"`
	Name        string `orm:"unique"`
	Status      int
	Description string
	Permissions []*Permission `orm:"rel(m2m)"`
}

func init() {
	orm.RegisterModel(new(Role))
}
func FindRoleById(id int) Role {
	o := orm.NewOrm()
	var role Role
	o.QueryTable(role).Filter("Id", id).One(&role, "Id", "Name", "Status", "Description")
	return role
}

func FindRoles() []*Role {
	o := orm.NewOrm()
	var role Role
	var roles []*Role
	o.QueryTable(role).All(&roles, "Id", "Name", "Status")
	return roles
}
func FindRolesByStatus(status int) []*Role {
	o := orm.NewOrm()
	var role Role
	var roles []*Role
	o.QueryTable(role).Filter("Status", status).All(&roles, "Id", "Name", "Status")
	return roles
}
func PageRoles(pageNo int, size int) util.Page {
	o := orm.NewOrm()
	var role Role
	var list []Role
	qs := o.QueryTable(role)
	count, _ := qs.Limit(-1).Count()
	qs.RelatedSel().Limit(size).Offset((pageNo-1)*size).All(&list, "Id", "Name", "Status")
	c, _ := strconv.Atoi(strconv.FormatInt(count, 10))
	for j := 0; j < len(list); j++ {
		o.Raw("select count(1) count from user where roles = ?", list[j].Id).QueryRow(&list[j].Description)
	}
	return util.PageUtil(c, pageNo, size, list)
}

func UserCountByRole(id int) int {
	o := orm.NewOrm()
	var count int = 0
	o.Raw("select count(1) count from user where roles = ?", id).QueryRow(&count)
	return count
}

func SaveRole(role *Role) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(role)
	return id, err
}

func UpdateRole(role *Role) {
	o := orm.NewOrm()
	o.Update(role, "Name", "Status", "Description")
}

func DeleteRole(role *Role) {
	o := orm.NewOrm()
	o.Delete(role)
}

func DeleteRolePermissionByRoleId(role_id int) {
	o := orm.NewOrm()
	o.Raw("delete from role_permissions where role_id = ?", role_id).Exec()
}

func SaveRolePermission(role_id int, permission_id int) {
	o := orm.NewOrm()
	o.Raw("insert into role_permissions (role_id, permission_id) values (?, ?)", role_id, permission_id).Exec()
}

func FindRolePermissionByRoleId(role_id int) []orm.Params {
	o := orm.NewOrm()
	var res []orm.Params
	o.Raw("select id, role_id, permission_id from role_permissions where role_id = ?", role_id).Values(&res, "id", "role_id", "permission_id")
	return res
}
